﻿namespace App_Code.Controls
{
    using System;
    using System.Collections.Generic;
    using System.Web;
    using System.IO;
    using System.Xml;
    using System.Text;
    using System.Text.RegularExpressions;

    /// <summary>
    /// Created By: Jason Deatherage
    /// Released: July 2010
    /// If you want to modify this code please leave my credit 
    /// in the code and link to my site on your webpage.
    /// Thanks.
    /// 
    /// This class refreshes the movie data after the edit settings box has left and 
    /// after the alotted time has past to refresh the data from netflix.
    /// </summary>
    public class MoviesForMyBlog
    {
        private string dataSource = AppDomain.CurrentDomain.GetData("DataDirectory").ToString();

        private XmlNode node1;
        private XmlNodeList genrefilter;
        public XmlNodeList nodeInstantPlayCount, nodeDiscShippedCount, nodeMovieRatings;

        public MoviesForMyBlog()
        {

        }

        public void RefreshMovieData()
        {

            //This is the document for the movie data
            XmlDocument xmlDoc = new XmlDocument();

            //This is the XML documents for the user settings
            XmlDocument xmlDoc1 = new XmlDocument();

            xmlDoc.Load(dataSource + @"\moviesformyblognetflixdata.xml");
            XmlNode node = xmlDoc.SelectSingleNode("/data");



            xmlDoc1.Load(dataSource + @"\moviesformyblognetflixuser.xml");
            XmlNode nodeInstantPlay = xmlDoc1.SelectSingleNode("//DisplayQuantity/control[@id='InstantPlay']");
            XmlNode nodeDiscShipped = xmlDoc1.SelectSingleNode("//DisplayQuantity/control[@id='DiscsShipped']");

            //Creates XML nodes to get the security requirments
            node1 = xmlDoc1.SelectSingleNode("//RequestToken/consumerkey");
            XmlNode node2 = xmlDoc1.SelectSingleNode("//AccessToken/oauth_token");
            XmlNode node3 = xmlDoc1.SelectSingleNode("//AccessToken/user_id");
            XmlNode node4 = xmlDoc1.SelectSingleNode("//AccessToken/oauth_token_secret");

            //Document that stores the last movies watched
            XmlDocument xmlDoc2 = new XmlDocument();
            XmlNode nodeDeclaration = xmlDoc2.CreateNode(XmlNodeType.XmlDeclaration, "", "");
            xmlDoc2.AppendChild(nodeDeclaration);
            XmlElement xeRoot = xmlDoc2.CreateElement("data");
            xmlDoc2.AppendChild(xeRoot);
            XmlNode newdata;
            XmlElement xeInstantPlay = xmlDoc2.CreateElement("InstantPlay");
            xeInstantPlay.SetAttribute("id", "Empty");

            xeRoot.AppendChild(xeInstantPlay);
            XmlElement xeDiscsShipped = xmlDoc2.CreateElement("DiscsShipped");
            xeDiscsShipped.SetAttribute("id", "Empty");

            xeRoot.AppendChild(xeDiscsShipped);

            XmlDocument xmlDoc3 = new XmlDocument();

            //Make request to web service to get the movies that have been watched
            moviesformyblognetflix.Service ws = new moviesformyblognetflix.Service();

            //Inserts the webservice data into one xmlDoc file
            if (Convert.ToBoolean(nodeInstantPlay.Attributes["active"].InnerText) == true)
            {

                string strMoviesWatched = ws.RequestLastMoviesWatched(node1.InnerText, node2.InnerText
                    + "&" + node3.InnerText + "&" + node4.InnerText, Convert.ToInt32(nodeInstantPlay.Attributes["quantity"].InnerText));

                xmlDoc3.LoadXml(strMoviesWatched);
                newdata = xmlDoc3.RemoveChild(xmlDoc3.DocumentElement);
                xeInstantPlay.AppendChild(xmlDoc2.ImportNode(newdata, true));
                xeInstantPlay.SetAttribute("id", "Full");


            }

            //Inserts the webservice data into one xmlDoc file
            if (Convert.ToBoolean(nodeDiscShipped.Attributes["active"].InnerText) == true)
            {

                string strDiscsShipped = ws.RequestLastDiscsRented(node1.InnerText, node2.InnerText
                    + "&" + node3.InnerText + "&" + node4.InnerText, Convert.ToInt32(nodeDiscShipped.Attributes["quantity"].InnerText));

                xmlDoc3.LoadXml(strDiscsShipped);
                newdata = xmlDoc3.RemoveChild(xmlDoc3.DocumentElement);
                xeDiscsShipped.AppendChild(xmlDoc2.ImportNode(newdata, true));
                xeDiscsShipped.SetAttribute("id", "Full");


            }


            //*******MPAA Filtering*******//
            XmlNodeList mpaafilters = xmlDoc1.SelectNodes("//FilterSettings/Ratings/control[@active='False']");

            if (mpaafilters.Count > 0)
            {
                foreach (XmlNode nodefilter in mpaafilters)
                {
                    genrefilter = xmlDoc2.SelectNodes("//rental_history_item/category[@term=\"" + nodefilter.Attributes["id"].InnerText + "\"]");

                    if (genrefilter.Count > 0)
                    {
                        foreach (XmlNode nodefilter1 in genrefilter)
                        {
                            XmlNode noderemove1 = nodefilter1.ParentNode;
                            noderemove1.ParentNode.RemoveChild(noderemove1);
                        }
                    }
                }
            }

            //*******MPAA Filtering*******//

            //*******Genre Filtering*******//
            genrefilter = xmlDoc2.SelectNodes("//rental_history_item/category");

            foreach (XmlNode nodefilter in genrefilter)
            {
                XmlNodeList nodefilter1 = xmlDoc1.SelectNodes("//GenreFilters/Genre[@term=\"" + nodefilter.Attributes["term"].InnerText + "\"]");
                if (nodefilter1.Count > 0)
                {
                    XmlNode noderemove = nodefilter.ParentNode;
                    noderemove.ParentNode.RemoveChild(noderemove);

                }

            }
            //*******Genre Filtering*******//

            XmlElement elemRatingUser;
            XmlElement elemRatingMember;


            //Inserts the webservice data into one xmlDoc file
            if (Convert.ToBoolean(nodeInstantPlay.Attributes["active"].InnerText) == true)
            {
                nodeInstantPlayCount = xmlDoc2.SelectNodes("//InstantPlay/rental_history/rental_history_item");

                if (nodeInstantPlayCount.Count > 0)
                {

                    //This gets the links to the movies that is required to pull the ratings for each film
                    nodeMovieRatings = xmlDoc2.SelectNodes("//InstantPlay/rental_history/rental_history_item/link[1]");

                    string strMovieTitles = "";
                    int counter = 0;

                    //Loops through the nodelist to get the comma delimted string for the next web service
                    while (counter < nodeMovieRatings.Count)
                    {
                        strMovieTitles = strMovieTitles + nodeMovieRatings[counter].Attributes["href"].InnerText + ",";
                        counter++;

                    }

                    //Queries the webservices for movie ratings and predicted ratings
                    moviesformyblognetflix.Service mr = new moviesformyblognetflix.Service();
                    string strUserRating = mr.RequestMovieRatings(node1.InnerText, node2.InnerText
                        + "&" + node3.InnerText + "&" + node4.InnerText, strMovieTitles);
                    string strMemberRating = mr.RequestMovieRatingsPredicted(node1.InnerText, node2.InnerText
                        + "&" + node3.InnerText + "&" + node4.InnerText, strMovieTitles);

                    //*****Combines both queries into one xml file*****//

                    xmlDoc3.LoadXml(strUserRating);
                    newdata = xmlDoc3.RemoveChild(xmlDoc3.DocumentElement);
                    elemRatingUser = xmlDoc2.CreateElement("ratings_user");
                    xeInstantPlay.AppendChild(elemRatingUser);
                    elemRatingUser.AppendChild(xmlDoc2.ImportNode(newdata, true));

                    xmlDoc3.LoadXml(strMemberRating);
                    newdata = xmlDoc3.RemoveChild(xmlDoc3.DocumentElement);
                    elemRatingMember = xmlDoc2.CreateElement("ratings_members");
                    xeInstantPlay.AppendChild(elemRatingMember);
                    elemRatingMember.AppendChild(xmlDoc2.ImportNode(newdata, true));
                    //*****Combines both queries into one xml file*****//


                }
            }

            //Inserts the webservice data into one xmlDoc file
            if (Convert.ToBoolean(nodeDiscShipped.Attributes["active"].InnerText) == true)
            {
                nodeDiscShippedCount = xmlDoc2.SelectNodes("//DiscsShipped/rental_history/rental_history_item");
                if (nodeDiscShippedCount.Count > 0)
                {

                    //This gets the links to the movies that is required to pull the ratings for each film
                    nodeMovieRatings = xmlDoc2.SelectNodes("//DiscsShipped/rental_history/rental_history_item/link[1]");

                    string strMovieTitles = "";
                    int counter = 0;

                    //Loops through the nodelist to get the comma delimted string for the next web service
                    while (counter < nodeMovieRatings.Count)
                    {
                        strMovieTitles = strMovieTitles + nodeMovieRatings[counter].Attributes["href"].InnerText + ",";
                        counter++;

                    }

                    //Queries the webservices for movie ratings and predicted ratings
                    moviesformyblognetflix.Service mr = new moviesformyblognetflix.Service();
                    string strUserRating = mr.RequestMovieRatings(node1.InnerText, node2.InnerText
                        + "&" + node3.InnerText + "&" + node4.InnerText, strMovieTitles);
                    string strMemberRating = mr.RequestMovieRatingsPredicted(node1.InnerText, node2.InnerText
                        + "&" + node3.InnerText + "&" + node4.InnerText, strMovieTitles);

                    //*****Combines both queries into one xml file*****//

                    xmlDoc3.LoadXml(strUserRating);
                    newdata = xmlDoc3.RemoveChild(xmlDoc3.DocumentElement);
                    elemRatingUser = xmlDoc2.CreateElement("ratings_user");
                    xeDiscsShipped.AppendChild(elemRatingUser);
                    elemRatingUser.AppendChild(xmlDoc2.ImportNode(newdata, true));

                    xmlDoc3.LoadXml(strMemberRating);
                    XmlNode oldroot2 = xmlDoc3.RemoveChild(xmlDoc3.DocumentElement);
                    elemRatingMember = xmlDoc2.CreateElement("ratings_members");
                    xeDiscsShipped.AppendChild(elemRatingMember);
                    elemRatingMember.AppendChild(xmlDoc2.ImportNode(newdata, true));
                    //*****Combines both queries into one xml file*****//

                }
            }

            xmlDoc2.Save(dataSource + @"\moviesformyblognetflixdata.xml");


        }
    }
}